package com.gomoku;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;

public class GameFrame extends JFrame {
    private GameLogic gameLogic;
    private GameMode gameMode;
    private boolean isBlackTurn;
    private AIThread aiThread;

    private JButton[][] boardButtons;
    private JLabel statusLabel;
    private JButton undoButton;
    private JButton restartButton;
    private JButton mainMenuButton;

    public GameFrame(GameMode mode) {
        this.gameMode = mode;
        this.gameLogic = new GameLogic();
        this.isBlackTurn = true;

        setTitle("五子棋 - " + mode.toString());
        setSize(600, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setResizable(false);

        initComponents();

        if (mode == GameMode.HUMAN_VS_AI && gameLogic.getCurrentPlayer() == 2) {
            makeAIMove();
        }
    }

    private void initComponents() {
        JPanel boardPanel = new JPanel(new GridLayout(GameLogic.BOARD_SIZE, GameLogic.BOARD_SIZE));
        boardButtons = new JButton[GameLogic.BOARD_SIZE][GameLogic.BOARD_SIZE];

        for (int i = 0; i < GameLogic.BOARD_SIZE; i++) {
            for (int j = 0; j < GameLogic.BOARD_SIZE; j++) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(40, 40));
                button.setOpaque(true);
                button.setBorder(BorderFactory.createLineBorder(Color.BLACK));
                button.setBackground(new Color(220, 179, 92));

                final int row = i;
                final int col = j;
                button.addActionListener(e -> handleButtonClick(row, col));

                boardButtons[i][j] = button;
                boardPanel.add(button);
            }
        }

        statusLabel = new JLabel("黑方回合", JLabel.CENTER);
        statusLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));

        undoButton = new JButton("悔棋");
        undoButton.addActionListener(e -> {
            gameLogic.undoMove();
            updateBoard();
            updateStatus();

            if (gameMode == GameMode.HUMAN_VS_AI && gameLogic.getCurrentPlayer() == 2) {
                makeAIMove();
            }
        });

        restartButton = new JButton("重新开始");
        restartButton.addActionListener(e -> {
            gameLogic.resetGame();
            updateBoard();
            updateStatus();

            if (gameMode == GameMode.HUMAN_VS_AI && gameLogic.getCurrentPlayer() == 2) {
                makeAIMove();
            }
        });

        mainMenuButton = new JButton("主菜单");
        mainMenuButton.addActionListener(e -> {
            dispose();
            new MainMenu().setVisible(true);
        });

        JPanel controlPanel = new JPanel(new GridLayout(1, 3));
        controlPanel.add(undoButton);
        controlPanel.add(restartButton);
        controlPanel.add(mainMenuButton);

        add(boardPanel, BorderLayout.CENTER);
        add(statusLabel, BorderLayout.NORTH);
        add(controlPanel, BorderLayout.SOUTH);
    }

    private void handleButtonClick(int row, int col) {
        if (gameLogic.makeMove(row, col)) {
            updateBoard();

            if (gameLogic.isGameOver()) {
                String winner = gameLogic.getCurrentPlayer() == 1 ? "黑方" : "白方";
                JOptionPane.showMessageDialog(this, winner + "获胜!", "游戏结束", JOptionPane.INFORMATION_MESSAGE);
            } else {
                if (gameMode == GameMode.HUMAN_VS_AI && gameLogic.getCurrentPlayer() == 2) {
                    makeAIMove();
                }
            }
        }
    }

    private void makeAIMove() {
        if (aiThread != null && aiThread.isAlive()) {
            aiThread.interrupt();
        }

        aiThread = new AIThread();
        aiThread.start();
    }

    private void updateBoard() {
        int[][] board = gameLogic.getBoard();

        for (int i = 0; i < GameLogic.BOARD_SIZE; i++) {
            for (int j = 0; j < GameLogic.BOARD_SIZE; j++) {
                Color color;
                switch (board[i][j]) {
                    case 1: color = Color.BLACK; break;
                    case 2: color = Color.WHITE; break;
                    default: color = new Color(220, 179, 92); break;
                }
                boardButtons[i][j].setBackground(color);
            }
        }

        updateStatus();
    }

    private void updateStatus() {
        if (gameLogic.isGameOver()) {
            statusLabel.setText("游戏结束");
        } else {
            String currentPlayer = gameLogic.getCurrentPlayer() == 1 ? "黑方" : "白方";
            statusLabel.setText(currentPlayer + "回合");
        }
    }

    private class AIThread extends Thread {
        @Override
        public void run() {
            try {
                // 模拟AI思考
                Thread.sleep(500);

                // 简单的AI逻辑：随机选择一个空位
                List<int[]> emptySpots = new ArrayList<>();
                for (int i = 0; i < GameLogic.BOARD_SIZE; i++) {
                    for (int j = 0; j < GameLogic.BOARD_SIZE; j++) {
                        if (gameLogic.getBoard()[i][j] == 0) {
                            emptySpots.add(new int[]{i, j});
                        }
                    }
                }

                if (!emptySpots.isEmpty()) {
                    Random random = new Random();
                    int[] move = emptySpots.get(random.nextInt(emptySpots.size()));

                    SwingUtilities.invokeLater(() -> {
                        gameLogic.makeMove(move[0], move[1]);
                        updateBoard();

                        if (gameLogic.isGameOver()) {
                            String winner = gameLogic.getCurrentPlayer() == 1 ? "黑方" : "白方";
                            JOptionPane.showMessageDialog(GameFrame.this, winner + "获胜!", "游戏结束", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                }
            } catch (InterruptedException e) {
                // 用户可能已经进行了其他操作，忽略
            }
        }
    }
}

enum GameMode {
    TWO_PLAYER("双人对战"),
    HUMAN_VS_AI("人机对战"),
    ONLINE("联机对战");

    private String displayName;

    GameMode(String displayName) {
        this.displayName = displayName;
    }

    @Override
    public String toString() {
        return displayName;
    }
}